package com.smart.manager.member.repository;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.bodys.RMemberMaterialPig;
import com.smart.manager.member.entities.bodys.RMemberMaterialProps;
import com.smart.manager.member.entities.enums.PropsKind;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.member.entities.views.MemberPigView;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.product.entities.enums.PigStatus;
import com.smart.manager.product.entities.enums.ServeTask;
import com.smart.manager.product.entities.models.PigGoods;
import com.smart.manager.product.entities.models.PigLevel;
import com.smart.manager.product.entities.models.PropsServe;
import com.smart.manager.product.entities.models.query.QPigLevel;
import com.smart.manager.product.entities.models.query.QPropsServe;
import com.smart.manager.product.entities.views.PigLevelView;
import com.smart.manager.product.entities.views.PropsComboView;
import com.smart.manager.product.entities.views.query.QPropsComboView;
import com.smart.manager.work.entities.assembler.WorkOrder;
import com.smart.manager.work.entities.enums.PigOrderKind;
import com.smart.manager.work.entities.enums.PigOrderStatus;
import com.smart.manager.work.repository.PigOrderRepository;
import com.smart.service.remind.RemindService;
import com.smart.wap.service.BatchService;
import io.ebean.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 玩家猪猪
 *
 * @author leo
 * @date 2023/09/22
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class MemberMaterialPigRepository {

    private final BatchService batchService;
    private final MemberMaterialPropsRepository materialPropsRepository;
    private final MemberAccountRepository memberAccountRepository;
    private final PigOrderRepository pigOrderRepository;
    private final RemindService remindService;

    public Page<MemberMaterialPig> pageList(RMemberMaterialPig.SearchBody search) {
        QMemberMaterialPig query = new QMemberMaterialPig();
        Opt.ofBlankAble(search.getMemberPhone()).ifPresent(x -> query.member.phoneNumber.contains(x));
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        Opt.ofBlankAble(search.getRfid()).ifPresent(x -> query.rfid.beaconMac.contains(x));
        Opt.ofBlankAble(search.getBreed()).ifPresent(x -> query.breed.code.eq(x));
        Opt.ofBlankAble(search.getName()).ifPresent(x -> query.name.contains(x));
        Opt.ofBlankAble(search.getPigsty()).ifPresent(x -> query.pigsty.code.eq(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<MemberMaterialPig>().load(query.findPagedList());
    }

    public Integer getReserve(Long member) {
        List<PigStatus> wait = List.of(PigStatus.WAIT, PigStatus.NORMAL, PigStatus.OUT);
        List<Integer> list = new QMemberMaterialPig().member.id.eq(member).status.in(wait).select(QMemberMaterialPig.Alias.reserveFund).findSingleAttributeList();
        int a = 0;
        for (Integer integer : list) {
            a = a + integer;
        }
        return a;
    }


    /**
     * 生成一只猪
     *
     * @param goods      商品
     * @param isFull     是否全价_是否有套餐
     * @param memberView 所属用户
     * @return 猪
     */
    @Transactional(rollbackFor = Exception.class)
    public MemberMaterialPig addPig(PigGoods goods, Boolean isFull, MemberView memberView, Integer months) {

        //查找猪仔等级
        PigLevel level = new QPigLevel().day.eq(goods.getDayNum()).breed.eq(goods.getBreed()).setMaxRows(1).findOne();
        Assert.notNull(level, "猪猪的等级规则匹配失败");
        //生成猪仔
        MemberMaterialPig pig = new MemberMaterialPig();
        String pigCode = IdUtil.getSnowflakeNextIdStr().substring(2, 9);
        if (isFull) pig.setChicken(goods.getChicken());
        pig.setCode(pigCode)
                .setTotalConsume(isFull ? goods.getFullPrice() + goods.getReserveFund() : goods.getPrice() + goods.getReserveFund())
                .setName(goods.getBreed().getName())
                .setStatus(PigStatus.WAIT)
                .setIsFull(isFull)
                .setBreed(goods.getBreed())
                .setPigLevel(new PigLevelView().setId(level.getId()))
                .setMember(memberView)
                .setReserveFund(goods.getReserveFund())
                .setId(IdUtil.getSnowflakeNextId());
        PropsComboView one1 = new QPropsComboView().isPack.eq(true).setMaxRows(1).findOne();
        if (isFull && goods.getMonth() > 0) {
            //设置包月次数
            batchService.addListPlan(null, one1, pig.getMember().getId(), pig.getId(), goods.getMonth() * 30);
            //生成鸡蛋
            if (goods.getEgg() > 0) {
                memberAccountRepository.saveEgg(memberView.getId(), goods.getEgg());
            }
        }
        //设置兑换码
        if (ObjUtil.isNotNull(months) && months > 0) {
            pig.setTotalConsume(0).setReserveFund(0);
            batchService.addListPlan(null, one1, pig.getMember().getId(), pig.getId(), months * 30);
        }

        //生成改名卡
        PropsServe serve = new QPropsServe().task.eq(ServeTask.RECHRISTEN).setMaxRows(1).findOne();
        if (ObjUtil.isNotNull(serve)) {
            RMemberMaterialProps.EditBody durable = new RMemberMaterialProps.EditBody()
                    .setName(serve.getName())
                    .setIcon(serve.getIcon())
                    .setCode(serve.getCode())
                    .setNumber(1)
                    .setMember(memberView)
                    .setKind(PropsKind.L2)
                    .setDurable(0);
            //叠加改名卡
            materialPropsRepository.add(durable);
        }
        pig.insert();
        String content = String.format("%s%s天%s猪", pig.getBreed().getName(), level.getDay(), level.getKind().getLabel());
        remindService.sendMiniProgramsMsg(null, "新的待分配猪猪工单", content, true);
        //生成工单
        pigOrderRepository.createAWorkOrder(new MemberPigView().setId(pig.getId()), null, PigOrderKind.L1, PigOrderStatus.ALLOCATED, new WorkOrder.EnterTheCircleBody().setDay(goods.getDayNum()).setMode(goods.getMode()).setId(pig.getId()));
        return pig;
    }

    public void cs(Long memberId, Long pigId) {
        PropsComboView one1 = new QPropsComboView().isPack.eq(true).setMaxRows(1).findOne();
        batchService.addListPlan(null, one1, memberId, pigId, 3 * 30);
    }
}
